angular.module 'data-srv', []
.factory 'paginationFactory', ($log, $http, $rootScope, $q, $ionicPopup, $state,showToast) ->
    loadDataFlag = true
    DataFactory = (ctrl, url) ->
        logger = $log.getInstance "paginationFactory(#{ctrl})"
        $watch = {}
        orderData = []   # 保存订单数据
        canLoadMore = false      # 是否可以继续加载
        params = {page: 1, pagesize: 10}

        getData = (setData, innerParams) -> # 如果setData，则会立即将数据传给回调函数
            _.extend params, innerParams
            $http.get(url, {params: params, animate: false})
            .success (resp) ->
                console.log 'resp',resp
                if resp.status == '0'
                    if params.page == 1 # 如果是reload
                        orderData = resp.body
                    else # 如果是loadMore
                        console.log 'canLoadMore',canLoadMore
                        orderData.push.apply orderData, resp.body
                    if resp.body.length < params.pagesize then canLoadMore = false
                    else canLoadMore = true
                    console.log canLoadMore
                    params.page += 1 # 起始点增加返回的数据长度
                    stateName = $state.current.name
                    if setData and _.has $watch, stateName
                        logger.log "call back #{$state.current.name}"
                        $watch[stateName] orderData
                else
                    canLoadMore = false
            .error ->
                showToast '您的网络又调皮了'

        canLoadMore: ->
            if canLoadMore == undefined then false
            else canLoadMore

        # 需要更新数据时，请调用reload方法
        # 如果setData为true，reload方法会调用当前view对应state里的回调函数
        reload: (setData = false, innerParams = undefined) ->
            logger.info 'reload data'
            params.page = 1
            getData(setData, innerParams)

        loadMore: ->
            if canLoadMore
                logger.log 'loadMore data',canLoadMore
                getData(true)

        # 需要获取order数据，请传递一个回调函数来调用watch方法，
        # watch方法会立即将数据给予调用者
        watch: (func) ->
            if !_.isFunction(func)
                throw "watch param is not a function!"
            key = $state.current.name
            $watch[key] = func
            logger.log "key: #{key}\t$watch size: #{_.keys($watch).length}"
            func orderData

            # 如果调用了watch方法，一定要监听$scope的$destory事件，
            # 并在$destory事件发生时调用这里返回的函数，
            # 不然会发生内存泄露
            -> delete $watch[key]
